import os
import re
import math
import pandas as pd
import numpy as np
from wifi_algo import dbm_to_distance
from wifi_algo import read_wifi_data
from wifi_algo import three_point_location



def get_matching_routers(wifi_dict, router_coords):
    """
    函数：仅通过BSSID匹配路由器，按信号强度（dBm）选择前3个最强信号
    参数：
        wifi_dict - 扫描的WiFi数据字典，格式：{(SSID, BSSID): 信号强度dBm}
        router_coords - 已知路由器坐标DataFrame（含BSSID、路由器横坐标X、路由器纵坐标Y）
    返回：
        my_coordinates - 前3个最强信号路由器的坐标列表：[(x1,y1), (x2,y2), (x3,y3)]
        my_distance - 对应路由器的距离列表：[d1, d2, d3]
    """
    # 1. 预处理已知路由器数据：统一BSSID为小写（避免大小写匹配失败）
    router_coords_copy = router_coords.copy()
    router_coords_copy['BSSID_lower'] = router_coords_copy['BSSID'].str.lower().str.strip()    
    # 2. 收集所有匹配的路由器（仅按BSSID匹配）
    matched_results = []
    for (_, scan_bssid), scan_dbm in wifi_dict.items():
        # 统一扫描的BSSID格式
        scan_bssid_lower = scan_bssid.lower().strip()
        # 仅通过BSSID匹配（忽略SSID）
        match_mask = (router_coords_copy['BSSID_lower'] == scan_bssid_lower)
        matched_routers = router_coords_copy[match_mask]
        # 若匹配到至少一个路由器，取第一个匹配结果的坐标
        if len(matched_routers) >= 1:
            router = matched_routers.iloc[0]
            x = router['路由器横坐标X']
            y = router['路由器纵坐标Y']
            # 存储：(信号强度dBm, x, y, 距离)，dBm用于排序（值越大信号越强）
            distance = dbm_to_distance(scan_dbm)
            matched_results.append((scan_dbm, x, y, distance))
    # 3. 按信号强度降序排序（dBm值大的排前面）
    matched_results.sort(reverse=True, key=lambda x: x[0])
    # 4. 检查是否至少有3个匹配结果
    if len(matched_results) < 3:
        raise ValueError(f"仅匹配到{len(matched_results)}个路由器，至少需要3个！")
    # 5. 选择前3个最强信号的结果
    top3_results = matched_results[:3]
    # 6. 提取坐标和距离
    my_coordinates = [(round(x, 2), round(y, 2)) for _, x, y, _ in top3_results]
    my_distance = [d for _, _, _, d in top3_results]
    # 打印筛选结果
    print(f"共匹配到{len(matched_results)}个路由器，按信号强度选择前3个：")
    for i, (dbm, x, y, d) in enumerate(top3_results, 1):
        print(f"  第{i}名：BSSID匹配 | 信号强度{dbm}dBm | 坐标({round(x,2)},{round(y,2)}) | 距离{d}米")
    return my_coordinates, my_distance
    



def get_coordinates(txt_file_path = "test.txt"):
    # 1. 读取数据（test.txt、point_coords.csv、router_coords.csv）
    wifi_dict = read_wifi_data(txt_file_path)
    # print(wifi_dict)
    # 加载坐标数据（确保CSV文件路径正确）
    try:
        router_coords = pd.read_csv("router_coords.csv")
        print(f"\n成功加载坐标数据：{len(router_coords)}个路由器")
    except Exception as e:
        print(f"\n加载CSV文件失败：{e}")
        exit()
    # print(router_coords.head())
    # 2. 匹配有效路由器
    my_coordinates, my_distance = get_matching_routers(wifi_dict, router_coords)
    # 3. 三角定位计算检测点坐标
    loc_result = three_point_location(my_coordinates, my_distance)
    if loc_result is None:
        print("定位计算失败，请检查数据或算法实现！")
        return None
    else:
        loc_result = (max(0, min(1000, loc_result[0])), max(0, min(1000, loc_result[1])))
    print(f"\n检测点最终坐标：X={loc_result[0]}, Y={loc_result[1]}")
    return loc_result



# -------------------------- 主流程执行 --------------------------
if __name__ == "__main__":
    result = get_coordinates()
    point_coords = pd.read_csv("point_coords.csv")
    print("\n检测点与所有已知点的距离：")
    dist_list = []
    for idx, row in point_coords.iterrows():
        px, py = row['横坐标X'], row['纵坐标Y']
        dist = math.sqrt((result[0]-px)**2 + (result[1]-py)**2)
        dist_list.append(dist)
    # 输出距离最小的点
    min_dist = min(dist_list)
    min_index = dist_list.index(min_dist)
    print(f"{point_coords.iloc[min_index]['点位编号']}")
    print(f"距离最近的点索引：{min_index}，坐标：({point_coords.iloc[min_index]['横坐标X']}, {point_coords.iloc[min_index]['纵坐标Y']})，距离：{min_dist}米")
